# coding:utf-8
'''
Created on 2013-5-30

@author: charliu
'''

import optparse
import sys
import time
import csv
import math

from pylib import android_commands, surface_stats_collector

    
def getPhoneInfo(adb, writer):
    #cpu = adb.RunShellCommand('getprop ro.product.cpu.abi')
    version = adb.RunShellCommand('getprop ro.build.version.release')
    phone_model = adb.RunShellCommand('getprop ro.product.model')
    phone_memory = adb.RunShellCommand('cat /proc/meminfo')
    phone_cpu = adb.RunShellCommand('cat /proc/cpuinfo')
    writer.writerow(['手机型号：' + phone_model[0]])
    writer.writerow(['手机CPU：' + phone_cpu[0]])
    writer.writerow(['手机内存：' + phone_memory[0]])
    writer.writerow(['系统版本：' + version[0]])
    writer.writerow([''])

def calculate_standard_deviation(values, average_value):
    tmp_sum = 0
    for value in values:
        tmp = value - average_value
        tmp_sum += (tmp * tmp)
    return math.sqrt(tmp_sum / len(values))
    
    

def calculateResult(all_fps, writer):
    sum_fps = 0
    bad_data_count = 0
    right_fps = []
    for fps in all_fps:
        if fps <= 3:
            bad_data_count += 1
        else:
            right_fps.append(fps)
            sum_fps += fps
    average_fps = sum_fps / (len(all_fps) - bad_data_count)
    writer.writerow([''])
    writer.writerow(['Fps 平均值：' + str(average_fps)])
    writer.writerow(['Fps 标准差：' + str(calculate_standard_deviation(right_fps, average_fps))])

def collect_fps(adb, collector, out_file, delay):
    fps = []
    csv_file = open(out_file, 'wb')
    writer = csv.writer(csv_file)
    getPhoneInfo(adb, writer)
    try:
        collector.Start()
        while True:
            time.sleep(delay)
            results = collector.SampleResults()
            if not results:
                continue
            fps.append(results[0].value)
            results[0].print_str()
            writer.writerow([results[0].value])
    except KeyboardInterrupt as e:
        collector.Stop()
    finally:
        calculateResult(fps, writer)
        csv_file.flush()
        csv_file.close()

def main(argv):
    usage = u"""
      使用方法：
      example: python fpsmonitor.py -a com.tencent.mobileqq/com.tencent.mobileqq.activity.MainActivity
      -a --activity 指定要测试的 Activity,(必填参数)
      -f --frequency 采样频率，单位为秒，默认为0.5s （可选参数)
      -d --device 有多个手机连接电脑，需指定 Serial number（可选参数)
      -o --outfile 测试结果输出文件名,默认为 fps_result.csv（可选参数)
    """
    parser = optparse.OptionParser(usage)
    parser.add_option('-d', '--device', help='Serial number of device we should use.')
    parser.add_option('-f', '--frequency', dest='frequency', default=0.5, type='float', help='Time in seconds to sleep between updates.')
    parser.add_option('-a', '--activity', dest='activity', help='The activity you want to test, like this: com.tencent.mobileqq/com.tencent.mobileqq.activity.ChatActivity')
    parser.add_option('-o', '--outfile', dest='outfile', default='fps_result.csv', help='The result output file')
    
    options, args = parser.parse_args(argv)
    if not options.activity:
        print(u'-a 参数--activity不能为空')
        parser.print_help()
        exit(0)
    adb = android_commands.AndroidCommands(options.device)
    collector = surface_stats_collector.SurfaceStatsCollector(adb, options.activity, options.frequency)
    collector.DisableWarningAboutEmptyData()
    collect_fps(adb, collector, options.outfile, options.frequency)

if __name__ == '__main__':
    main(sys.argv)
